package com.dong8.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.dong8.R;
import com.dong8.resp.Resp;
import com.dong8.sys.Constants;
import com.dong8.sys.MyApp;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.ToastUtil;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class InputTelephoneActivity extends Activity implements OnClickListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input_telephone);

		((TextView) findViewById(R.id.tv_title)).setText("输入注册手机号码");
		findViewById(R.id.ibBack).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		
		((MyApp)getApplicationContext()).addActivity(this);
	}

	protected void onDestroy()
	{
		super.onDestroy();
		((MyApp)getApplicationContext()).removeActivity(this);
	}
	
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.ibBack:
			finish();
			break;

		case R.id.login:
			getData();
			break;
		}
	}

	private void getData() 
	{
		final String tel = ((EditText) findViewById(R.id.tel)).getText().toString();
		if (tel.length() == 0) 
		{
			ToastUtil.showToastWithAlertPic("请输入手机号码");
			return;
		}

		if(!isMobileNO(tel))
		{
			ToastUtil.showToastWithAlertPic("您输入手机号码不正确，请重新输入");
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				super.onSuccess(response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.code == 0) {
					Intent intent = new Intent(InputTelephoneActivity.this, VerifyCodeActivity.class);
					intent.putExtra("code", ruser.data);
					intent.putExtra("tel", tel);
					startActivity(intent);
				} else {
					ToastUtil.showToastWithAlertPic(ruser.mesg);
				}
			}

			public void onFailure(Throwable ble) {
			}
		};

		RequestParams params = new RequestParams();
		params.put("data", tel);
		MgqRestClient.get(Constants.USER_CHECK_TEL, params, loginHandler);
	}
	
	public boolean isMobileNO(String mobiles) 
	{
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
}
